﻿using Comm;
using FastReport;
using FastReport.Export.Dbf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Web.UI.WebControls;
using System.Windows.Forms;

namespace CJGL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void 系统配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigForm passfrom = new ConfigForm();


            if (passfrom.ShowDialog(this) == DialogResult.OK)
            {

            }
        }
        TCPHelp1 scanner1 = new TCPHelp1();
        private void Form1_Load(object sender, EventArgs e)
        {
            //加载配置
            ClsParmart.LoadPar();
            scanner1.finPrint += Scanner1_finPrint;

            //skinEngine1.SkinFile = "MacOS.ssk";
            string count = SqlDAL.GetHospitalList();
            if (count != "")
            {
                ZMSY = Convert.ToInt32(count);
                this.label8.Text = count;
            }
        }



        // int barCodeCount = 0;
        List<string> listcode = new List<string>();
        int ZMCount = 0;
        //剩余中码数量
        int ZMSY = 0;
        //读取到小码数据
        private void Scanner1_finPrint(string Mes)
        {
            Mes = Mes.Replace(" ", "");
         
            if (Mes != "NoRead")
            {
              
                string now = listcode.Find(a=>a== Mes);
                if (now != null)
                {
                    //输出报警
                    Aelar("小码重复采集"+ Mes);
                }
                else
                {
                    //已经满了一箱子了，需要停止输送带
                    if (listcode.Count == int.Parse(ClsParmart.ProCount))
                    {
                        //insetLog("小码数量已经足够请读取中码");
                        Aelar("小码数量已经足够请读取中码");
                    }
                    else
                    {
                        insetLog("读取到小码:" + Mes);
                        AddCode(Mes);
                        //已经满了一箱子了，需要停止输送带
                        if (listcode.Count == int.Parse(ClsParmart.ProCount))
                        {
                            // IOHelp.sendOpen(ClsParmart.alert_prot, 0);
                            // insetLog("小码数量已经足够请读取中码");
                          
                            Scanner2_finPrint("");
                        }
                    }
                }
            }
            else
            {
                //输出报警
                Aelar("小码未采集到");
            }
          
        }

        //读取到中码数据
        private void Scanner2_finPrint(string Mes)
        {
        

            DataTable tab= SqlDAL.GetBarCode();
            if (tab.Rows.Count == 0)
            {
                Aelar("中码数量不够，请导入中码");
            }
            else {
                Thread th1 = new Thread(new ParameterizedThreadStart(SC1));
                th1.Start(Mes);
                Mes = tab.Rows[0]["code_str"].ToString();
                int ID = Convert.ToInt32(tab.Rows[0]["ID"]);
                insetLog("获取中码:" + Mes);
               
                //准备上传数据
                AddRelationMode model = new AddRelationMode();
                    model.proid = int.Parse(ClsParmart.SelProId);
                    model.qty = int.Parse(ClsParmart.ProCount);
                    model.scancodes = "";
                    foreach (string item in listcode)
                    {
                        model.scancodes += item + "|";
                    }
                    model.scancodes=model.scancodes.TrimEnd('|');
                    model.bcode = Mes;
                   string isup= Three.AddRelation(model);
                if (isup == "")
                {
                    CodeClear();
                    IOHelp.sendClose(ClsParmart.alert_prot, 0);
                    insetLog("中码上传关联关系成功:" + Mes);
                    AddCode1(Mes);
                    IOHelp.sendClose(ClsParmart.alert_prot, 0);
                    int isok = SqlDAL.UpdateBarcode(ID);
                    if (isok == 0)
                    {
                        insetLog("修改中码状态失败:" + Mes);
                    }
                    else
                    {
                        //上传成功了打印标签
                        this.Invoke(new Action(() =>
                        {
                            this.lblZM.Text = ZMCount.ToString();
                            ZMSY = ZMSY - 1;
                            this.label8.Text = ZMSY.ToString();
                        }));
                    }

                    Report report1 = new Report();
                    report1.Load(@"print1.frx");
                    // report1.SetParameterValue("par1", mes);
                    report1.SetParameterValue("date", Mes);
                    report1.PrintSettings.ShowDialog = false;
                    report1.PrintSettings.Printer = ClsParmart.cboprint1;
                    report1.PrintSettings.Copies = Convert.ToInt32(ClsParmart.PrintCount);
                    report1.Print();
                }
                else
                {
                    Thread.Sleep(int.Parse(ClsParmart.SCYS));
                    Aelar("上传失败中码："+ Mes +"|"+ isup);
                }
              
            }

        }
   
        private void Aelar(string Mes)
        {
            insetLog(Mes);
            if(Mes== "小码未采集到" || Mes.Contains("小码重复采集")|| Mes.Contains("小码数量已经足够")||Mes.Contains("采集的数据错误"))
            {
                Thread th = new Thread(new ParameterizedThreadStart(tc1));
                th.Start(Mes); 
            }
            if (Mes == "中码未采集到"|| Mes.Contains("小码数量还不够")|| Mes.Contains("上传失败"))
            {
                Thread th = new Thread(new ParameterizedThreadStart(tc2));
                th.Start(Mes);
            }

            Thread th1 = new Thread(new ParameterizedThreadStart(bj));
            th1.Start(Mes);

        }


        bool Isaler = false;
        bool Istc1 = false;
        bool Istc2 = false;
        private void SC1(object Mespar)
        {
            //没有在报警的时候触发报警
            //  if (!Istc1)
            {
                //  insetLog("开始停输送线，延时时间："+ ClsParmart.SCYS);
                if (ClsParmart.YCTZ == "")
                {
                    ClsParmart.YCTZ = "1000";
                }
                if (ClsParmart.ZTBC == "")
                {
                    ClsParmart.ZTBC = "1000";
                }
                Thread.Sleep(int.Parse(ClsParmart.YCTZ));
                IOHelp.sendOpen(ClsParmart.alert_prot, 0);
                Thread.Sleep(int.Parse(ClsParmart.ZTBC));
                IOHelp.sendClose(ClsParmart.alert_prot, 0);
                // insetLog("启动输送线：" );
            }
        }
        //剔除1
        private void tc1(object Mespar)
        {
            //没有在报警的时候触发报警
          //  if (!Istc1)
            {
                Istc1 = true;
                Thread.Sleep(int.Parse(ClsParmart.TCYS1));
                IOHelp.sendOpen(ClsParmart.alert_prot, 3);
                Thread.Sleep(int.Parse(ClsParmart.Alter_time1));
                IOHelp.sendClose(ClsParmart.alert_prot, 3);
                Istc1 = false;
            }
        }
        //剔除2
        private void tc2(object Mespar)
        {
            //没有在报警的时候触发报警
          //  if (!Istc2)
            {
               // Istc2 = true;
               //// Thread.Sleep(int.Parse(ClsParmart.TCYS2));
               // IOHelp.sendOpen(ClsParmart.alert_prot, 4);
               // Thread.Sleep(int.Parse(ClsParmart.Alter_time2));
               // IOHelp.sendClose(ClsParmart.alert_prot, 4);
               // Istc2 = false;
            }
        }
        //报警
        private void bj(object Mespar)
        {
            //没有在报警的时候触发报警
          //  if (!Isaler)
            {
                Isaler = true;
                IOHelp.sendOpen(ClsParmart.alert_prot, 2);
                Thread.Sleep(int.Parse(ClsParmart.Alter_time3));
                IOHelp.sendClose(ClsParmart.alert_prot, 2);
                Isaler = false;
            }
        }




        private void insetLog(string mes)
        {
            WriteFileCls.InserLog(mes);
            mes = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss：") + mes;

            this.Invoke(new Action(() =>
            {
                this.listBox1.Items.Insert(0, mes);
            }));
        }

        private void AddCode(string mes)
        {

            listcode.Insert(0, mes);
            this.Invoke(new Action(() =>
            {
                this.listBox2.Items.Insert(0, mes);
                this.lblCodeNum.Text = listcode.Count.ToString();
            }));
        }
        private void AddCode1(string mes)
        {
            ZMCount++;
            this.Invoke(new Action(() =>
            {
                this.listBox3.Items.Insert(0, mes);
                this.lblZM.Text = ZMCount.ToString();
            }));
        }

        private void CodeClear()
        {
            listcode.Clear();
            this.Invoke(new Action(() =>
            {
                this.listBox2.Items.Clear();
                this.lblCodeNum.Text = listcode.Count.ToString();
            }));
        }


        private void bindcboHospital(string name)
        {
            this.Invoke(new Action(() =>
            {
                //加载医院数据
                List<DataItem> list = Three.GetpPoduct(1, name);
                this.cboHospital.DisplayMember = "pro_name";
                this.cboHospital.ValueMember = "pro_id";
                this.cboHospital.DataSource = list;
            }));

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //skinEngine1.SkinFile = "MacOS.ssk";
            bindcboHospital(this.textBox1.Text);
          
        }

        private void cboHospital_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cboHospital.SelectedIndex != -1)
            {
                ClsParmart.SelProId = cboHospital.SelectedValue.ToString();
                //赋值文件配置
                this.textBox2.Text = XML.read("SelProId_"+ ClsParmart.SelProId, "p.xml");
            }
            CodeClear();
        }

        private void button3_Click(object sender, EventArgs e)
        {
         
            button3.Enabled = false;
            UIEnabled(false);
            if (button3.Text == "启动")
            {
                if (cboHospital.SelectedIndex != -1)
                {
                    ClsParmart.SelProId = cboHospital.SelectedValue.ToString();
                    if (textBox2.Text == "")
                    {
                        insetLog("请输入小码关联中码数量");
                        button3.Enabled = true;
                        UIEnabled(true);
                        textBox2.Focus();
                        return;
                    }
                    else
                    {
                      

                        int count = 0;
                       bool issuss= int.TryParse(textBox2.Text,out count);
                        if (!issuss&& count<=0)
                        {
                            insetLog("小码关联中码数量只能输入大于0的纯数字");
                            button3.Enabled = true;
                            UIEnabled(true);
                            return;
                        }
                        else
                        {
                            ClsParmart.ProCount = count.ToString();
                            XML.write("SelProId_" + ClsParmart.SelProId, count.ToString(), "p.xml");
                        }
                    }

                    if (ZMSY == 0)
                    {
                        insetLog("中码数量不够，请导入！");
                        button3.Enabled = true;
                        UIEnabled(true);
                        return;
                    }


                    string isok = scanner1.Open(ClsParmart.scanner_ip1, ClsParmart.scanner_port1);
                    if (isok != "ok")
                    {
                        insetLog("连接小码采集器失败:" + isok);
                        button3.Enabled = true;
                        UIEnabled(true);
                        return;
                    }



                    isok = IOHelp.Open(ClsParmart.alert_prot, ClsParmart.Baudrate);
                    if (isok != "ok")
                    {
                        scanner1.Close();
                        insetLog("连接IO盒子失败:" + isok);
                        button3.Enabled = true;
                        UIEnabled(true);
                        return;
                    }
                 
                    insetLog("启动软件成功!");
                    button3.Enabled = true;
                    button3.Text = "停止";
                }
                else
                {
                    button1.Enabled = true;
                    UIEnabled(true);
                    insetLog("启动失败，清选择产品");
                }
            }
            else
            {

                IOHelp.Close();
                insetLog("IO停止成功!");
                scanner1.Close();
                insetLog("采集器1停止成功!");
                UIEnabled(true);
                button3.Text = "启动";
                button3.Enabled = true;
            }
        }

        private void UIEnabled(bool isEnabled)
        {
            button1.Enabled = isEnabled;
            cboHospital.Enabled = isEnabled;
            textBox2.Enabled = isEnabled;
            button2.Enabled = isEnabled;
            button4.Enabled= isEnabled;
            补打箱码ToolStripMenuItem.Enabled= isEnabled;
            //   button3.Enabled = isEnabled;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //让用户选择点击
            DialogResult result = MessageBox.Show("确认清空已扫描的小码吗？", "警告",
                                  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            //判断是否取消事件
            if (result == DialogResult.Yes)
            {
                CodeClear();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            scanner1.Close();
            IOHelp.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.listBox2.SelectedIndex == -1)
            {
                MessageBox.Show("请选择一个小码");
            }
            else { 
            //让用户选择点击
            DialogResult result = MessageBox.Show("确认删除选中的小码吗？", "警告",
                                  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            //判断是否取消事件
            if (result == DialogResult.Yes)
            {
                    string nowcode = this.listBox2.SelectedItem.ToString();
                listcode.Remove(this.listBox2.SelectedItem.ToString());
                this.listBox2.Items.Remove(this.listBox2.SelectedItem);
                this.lblCodeNum.Text = listcode.Count.ToString();
                insetLog("已经成功删除小码:" + nowcode);
            }
            }
        }

        private void 换肤ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            skinEngine1.SkinFile = "MacOS.ssk";
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                //加载医院数据
                List<DataItem> list = Three.GetpPoduct(1,"");
                this.cboHospital.DisplayMember = "pro_name";
                this.cboHospital.ValueMember = "pro_id";
            
                    this.cboHospital.DataSource = list;
                
            }));
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            insetLog("加载产品数据完毕！");
            button3.Enabled = true;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {

            insetLog("加载产品数据中....");
            button3.Enabled = false;
            backgroundWorker1.RunWorkerAsync();


        }

        private void button5_Click(object sender, EventArgs e)
        {
            //让用户选择点击
            DialogResult result = MessageBox.Show("确认复位所有硬件？", "警告",
                                  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            //判断是否取消事件
            if (result == DialogResult.Yes)
            {
                IOHelp.sendClose(ClsParmart.alert_prot, 8);
            }
        }

        private void 注册授权ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PassWord passfrom = new PassWord();
            if (passfrom.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Form1());
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            string file = e.Argument.ToString();
            using (StreamReader sR1 = new StreamReader(file))
            {
                string HospitalStr = sR1.ReadToEnd();
                List<string> list = HospitalStr.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
                DataTable dt = GetTableSchema();
                foreach (var item in list)
                {
                    if (item != "")
                    {
                        DataRow row = dt.NewRow();
                        row["code_str"] = item;
                        row["is_user"] = 0;
                        dt.Rows.Add(row);
                    }
                }
            string ss= SqlDbHelper.InsertTwo(dt);
                e.Result = ss;
            }

        }
        public static DataTable GetTableSchema()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("is_user", typeof(int));
            dt.Columns.Add("code_str", typeof(string));
            return dt;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "文本文件(*.txt)|*.txt"; //设置要选择的文件的类型

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回文件的完整路径      

                if (!backgroundWorker2.IsBusy)
                {
                    UIEnabled(false);
                    insetLog("导入中码数据开始，请等待.....");
                    backgroundWorker2.RunWorkerAsync(file);
                }
            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string mes=e.Result.ToString();
            if (mes == "")
            {
                insetLog("导入中码数据成功");
                string count = SqlDAL.GetHospitalList();
                if (count != "")
                {
                    ZMSY = Convert.ToInt32(count);
                    this.label8.Text = count;
                }
                UIEnabled(true);
            }
            else
            {
                insetLog("导入中码数据失败"+ mes);
                UIEnabled(true);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
          
            string mes1 = "12346578";
            Report report1 = new Report();
            report1.Load(@"print1.frx");
            // report1.SetParameterValue("par1", mes);
            report1.SetParameterValue("date", mes1);
            report1.PrintSettings.ShowDialog = false;
            report1.PrintSettings.Printer = ClsParmart.cboprint1;
            report1.Print();

        }

        private void 设置打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 mb = new Form2();
            mb.Show();
        }

        private void 删除错误中码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form3 passfrom = new Form3();
            if (passfrom.ShowDialog(this) == DialogResult.OK)
            {
                string count = SqlDAL.GetHospitalList();
                if (count != "")
                {
                    ZMSY = Convert.ToInt32(count);
                    this.label8.Text = count;
                }
            }
        }

        private void 补打箱码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form4 mb = new Form4();
            mb.Show();
        }
    }
}
